package com.laboratory.Process;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableTest2 {

	public static void main(String[] args) {

		// 新建 10 个线程，每个线程分别负责累加 1~10, 11~20, ..., 91~100
		long startTime = System.currentTimeMillis();
		List<FutureTask<Integer>> futureTasks = new ArrayList<>();
		int total = 0;
		for (int i = 0; i < 10; i++) {
			final int begin = i * 10 + 1;
			final int end = (i + 1) * 10;
			FutureTask<Integer> futureTask = new FutureTask<>(new Callable<Integer>() {
				@Override
				public Integer call() throws Exception {
					long startTime = System.currentTimeMillis();
					int result = 0;
					for (int j = begin; j <= end; j++) {
						result += j;
					}
					// Thread.sleep(200);
					System.out.printf("(%s) - 运行结束，结果为 %d, 运行时间为 %s\n", Thread.currentThread().getName(), result,
							System.currentTimeMillis() - startTime);
					return result;
				}
			});
			futureTasks.add(futureTask);
			Thread thread = new Thread(futureTask, "线程" + i);
			thread.start();
		}
		for (FutureTask<Integer> futureTask : futureTasks) {
			try {
				total += futureTask.get();
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			}
		}

		System.out.printf("(%s) - 运行结束，结果为 %d, 运行时间为 %s\n", Thread.currentThread().getName(), total,
				System.currentTimeMillis() - startTime);

	}

}
